package com.etoak.service.impl;

import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-03-04
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {
    @Override
    public Dishes getByName(String name) {
        return lambdaQuery().eq(Dishes::getName, name).one();
    }

    @Override
    public void add(Dishes dishes) {
        if (ObjectUtils.isNotEmpty(getByName(dishes.getName()))) {
            throw new CustomException("菜品名称重复！");
        }

        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    @Override
    public PageVO<DishesVO> list(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum, pageSize);
        List<DishesVO> dishesVOList = baseMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(dishesVOList);
        return new PageVO<>(pageInfo.getTotal(), dishesVOList);
    }

    @Override
    public void update(int id, Dishes dishes) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("菜品不存在！");
        }
        String dishesName = dishes.getName();
        if (StringUtils.isNotBlank(dishesName)) {
            Dishes saveDishes = getByName(dishesName);
            if (ObjectUtils.isNotEmpty(saveDishes) && !saveDishes.getId().equals(id)) {
                throw new CustomException("菜品名称重复！");
            }
        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    @Override
    public void delete(int id) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("菜品不存在！");
        }
        this.removeById(id);
    }
}
